import 'package:flutter/material.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/feedback_item.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/widgets/network_load_image.dart';
import 'package:flutter_syt/domain/widgets/photo_views_more_screen.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/fade_route.dart';
import 'package:flutter_syt/utils/global_date_time_format.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:provider/provider.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "feedbackDetail")
class FeedbackDetail extends StatefulWidget {
  final int id;
  final bool isMine;
  const FeedbackDetail(this.id, this.isMine);

  @override
  _FeedbackDetailState createState() => _FeedbackDetailState();
}

class _FeedbackDetailState extends State<FeedbackDetail> {
  bool isLoading = true;

  FeedbackDetailData? data;

  bool hasError = false;

  @override
  void initState() {
    getData();
    super.initState();
  }

  void getData() async {
    setState(() {
      isLoading = true;
    });
    try {
      data = await API.shared.feedback.detail(widget.id);
      hasError = false;
    } catch (e, stack) {
      hasError = true;
      debugPrint("$stack");
    }
    setState(() {
      isLoading = false;
    });
  }

  Widget loading() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "assets/icons/empty.png",
            width: 80,
            height: 80,
          ),
          Container(
            height: 12,
          ),
          Text(
            S.of(context).loading,
            style:
                TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14),
          ),
          Container(
            height: 20,
          ),
        ],
      ),
    );
  }

  Widget renderError() {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Image.asset(
            "assets/images/black_back.png",
            width: 30,
            height: 30,
          ),
          onPressed: ClickUtils.debounce(() {
            Navigator.of(context).pop();
          }),
        ),
      ),
      body: ViewStateErrorWidget(
        onPressed: ClickUtils.debounce(() {
          getData();
        }),
      ),
    );
  }

  Widget renderImages(List<String> images) {
    return Container(
      margin: EdgeInsets.only(top: 15),
      child: Wrap(
        spacing: 16,
        runSpacing: 16,
        children: [
          ...images
              .map(
                (e) => GestureDetector(
                  child: ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(8)),
                    child: NetworkLoadImage.loadNetworkImage(
                      // CachedNetworkImage(
                      // imageUrl: e,
                      e,
                      width: 95,
                      height: 95,
                      fit: BoxFit.cover,
                    ),
                  ),
                  onTap: ClickUtils.debounce(() {
                    Navigator.of(context).push(
                      FadeRoute(
                          page: PhotoViewMoreScreen(
                        imageRows: images,
                        defaultImage: images.indexOf(e),
                      )
                          // page: PhotoViewSimpleScreen(
                          //     imageProvider: CachedNetworkImageProvider(e)),
                          // PhotoView(
                          //     imageProvider: CachedNetworkImageProvider(e)),
                          ),
                    );
                  }),
                ),
              )
              .toList(),
        ],
      ),
    );
  }

  Widget renderListItem(String text, List<String> images) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 15.0),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: ThemeColor.dividerColor_grey,
            width: 0.5,
            style: BorderStyle.solid,
          ),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            text,
            style: FontStyles.headerTextStyle_16.copyWith(
              color: ThemeColor.colorBlack80,
              fontWeight: FontWeight.w500,
            ),
          ),
          if (images.length > 0) renderImages(images),
        ],
      ),
    );
  }

  Widget renderReply(FeedbackDetailItem e) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 15),
      child: Row(
        children: [
          Container(
            child: Row(
              children: [
                Container(
                  width: 24,
                  height: 24,
                  child: CircleAvatar(
                    backgroundImage: AssetImage("assets/images/avatar_1.png"),
                  ),
                ),
                SizedBox(
                  width: 6,
                ),
                Container(
                  child: Text(
                    S.of(context).qa_reply,
                    style: TextStyle(
                      color: Colors.black.withOpacity(0.4),
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Container(
              alignment: Alignment.centerRight,
              child: Text(
                '${formatDate(e.createTime)}',
                style: TextStyle(
                  color: Colors.black.withOpacity(0.4),
                  fontSize: 14,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget renderPage() {
    // List<String?> title = [
    //   data?.typeName ?? "",
    // ];
    // if (data!.subModule != '') {
    //   // title.insert(2, data!.subModule);
    //   title.add(data!.subModule);
    // }
    return Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: Text(
            S.of(context).feedback,
          ),
        ),
        body: Column(
          children: [
            Expanded(
              child: ListView(
                padding: EdgeInsets.all(15),
                children: [
                  Container(
                    width: double.infinity,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Consumer<UserInfo>(builder: (ctx, user, child) {
                          return Container(
                            width: 24,
                            height: 24,
                            child: CircleAvatar(
                              backgroundImage: NetworkImage(
                                user.avatar,
                              ),
                            ),
                          );
                        }),
                        SizedBox(
                          width: 15.0,
                        ),
                        Expanded(
                          child: Container(
                            child: Column(
                              children: [
                                Container(
                                  child: Row(
                                    // mainAxisAlignment:
                                    // MainAxisAlignment.spaceBetween,
                                    children: [
                                      Container(
                                        child: Text(
                                          '', // title.join('·'),
                                          style: TextStyle(
                                            color:
                                                Colors.black.withOpacity(0.4),
                                            fontSize: 14,
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ),
                                      Container(
                                        child: Text(
                                          '${formatDate(data!.createTime)}',
                                          style: TextStyle(
                                            color:
                                                Colors.black.withOpacity(0.4),
                                            fontSize: 14,
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                renderListItem(
                                  data!.content.text,
                                  data!.content.images,
                                ),
                                ...data!.list
                                    .map(
                                      (e) => e.itemType == 2
                                          ? Container(
                                              child: Column(
                                                children: [
                                                  renderReply(e),
                                                  renderListItem(
                                                    e.content.text,
                                                    e.content.images,
                                                  ),
                                                ],
                                              ),
                                            )
                                          : Container(),
                                    )
                                    .toList(),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
                margin: EdgeInsets.fromLTRB(0, 20.0, 0, 20.0),
                padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 6.0),
                decoration: BoxDecoration(
                  border: Border(
                    top: BorderSide(
                      color: ThemeColor.dividerColor_grey,
                      width: 0.5,
                      style: BorderStyle.solid,
                    ),
                  ),
                ),
                child: ElevatedButton(
                    child: Text(
                      S.of(context).feedback_again,
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    onPressed: ClickUtils.debounce(
                      () {
                        if (widget.isMine) {
                          Navigator.of(context).popUntil((route) {
                            // print(
                            //     'pageName: ${route.settings.name}, isFirst: ${route.isFirst}');
                            if (route.settings.name == 'feedback_page') {
                              return true;
                            }
                            return false;
                          });
                        } else {
                          DLog(data);
                          RouteManager.push(context,
                              RoutMapping.feedbackPage(data?.moduleId ?? 1));
                        }
                      },
                    ))),
          ],
        )
        //  Stack(
        //   children: [
        //     Container(
        //       padding: EdgeInsets.fromLTRB(
        //           15, 0, 15, kCurrentAppSafeInset.bottom + 60),
        //       child: ListView(
        //         children: [
        //           Container(
        //             width: double.infinity,
        //             child: Row(
        //               crossAxisAlignment: CrossAxisAlignment.start,
        //               children: [
        //                 Consumer<UserInfo>(builder: (ctx, user, child) {
        //                   return Container(
        //                     width: 24,
        //                     height: 24,
        //                     child: CircleAvatar(
        //                       backgroundImage: NetworkImage(
        //                         user.avatar,
        //                       ),
        //                     ),
        //                   );
        //                 }),
        //                 SizedBox(
        //                   width: 15.0,
        //                 ),
        //                 Expanded(
        //                   child: Container(
        //                     child: Column(
        //                       children: [
        //                         Container(
        //                           child: Row(
        //                             mainAxisAlignment:
        //                                 MainAxisAlignment.spaceBetween,
        //                             children: [
        //                               Container(
        //                                 child: Text(
        //                                   title.join('·'),
        //                                   style: TextStyle(
        //                                     color: Colors.black.withOpacity(0.4),
        //                                     fontSize: 14,
        //                                     fontWeight: FontWeight.w400,
        //                                   ),
        //                                 ),
        //                               ),
        //                               Container(
        //                                 child: Text(
        //                                   '${formatDate(data!.createTime)}',
        //                                   style: TextStyle(
        //                                     color: Colors.black.withOpacity(0.4),
        //                                     fontSize: 14,
        //                                     fontWeight: FontWeight.w400,
        //                                   ),
        //                                 ),
        //                               ),
        //                             ],
        //                           ),
        //                         ),
        //                         renderListItem(
        //                           data!.content.text,
        //                           data!.content.images,
        //                         ),
        //                         ...data!.list
        //                             .map(
        //                               (e) => e.itemType == 2
        //                                   ? Container(
        //                                       child: Column(
        //                                         children: [
        //                                           renderReply(e),
        //                                           renderListItem(
        //                                             e.content.text,
        //                                             e.content.images,
        //                                           ),
        //                                         ],
        //                                       ),
        //                                     )
        //                                   : Container(),
        //                             )
        //                             .toList(),
        //                       ],
        //                     ),
        //                   ),
        //                 ),
        //               ],
        //             ),
        //           ),
        //         ],
        //       ),
        //     ),
        //     Positioned(
        //       bottom: 20,
        //       left: 0,
        //       right: 0,
        //       child: Container(
        //         margin: EdgeInsets.fromLTRB(0, 20.0, 0, 20.0),
        //         padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 6.0),
        //         decoration: BoxDecoration(
        //           border: Border(
        //             top: BorderSide(
        //               color: ThemeColor.dividerColor_grey,
        //               width: 0.5,
        //               style: BorderStyle.solid,
        //             ),
        //           ),
        //         ),
        //         child: ElevatedButton(
        //             child: Text(
        //               S.of(context).feedback_again,
        //               style: TextStyle(fontWeight: FontWeight.bold),
        //             ),
        //             onPressed: ClickUtils.debounce(
        //               () {
        //                 Navigator.of(context).popUntil((route) {
        //                   print(
        //                       'pageName: ${route.settings.name}, isFirst: ${route.isFirst}');
        //                   if (route.settings.name == 'feedback_page') {
        //                     return true;
        //                   }
        //                   return false;
        //                 });
        //               },
        //             )),
        //       ),
        //     )
        //   ],
        // ),
        );
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return loading();
    }
    if (hasError) {
      return renderError();
    }
    return renderPage();
  }
}
